#include "tableviewex.h"
#include <QMenu>
#include <QDebug>
#include <QHeaderView>

TableViewEx::TableViewEx(QWidget *parent)
    : QTableView(parent)
{
    m_model = new QStandardItemModel(this);
    setModel(m_model);

    horizontalHeader()->setDefaultAlignment(Qt::AlignCenter);
    verticalHeader()->setDefaultAlignment(Qt::AlignCenter);

    setShowGrid(true);
    setGridStyle(Qt::DotLine);

    installEventFilter(this);
}

TableViewEx::~TableViewEx()
{

}

QStandardItemModel &TableViewEx::getModel()
{
    return *m_model;
}

void TableViewEx::setHeaders(QStringList list)
{
    m_model->setHorizontalHeaderLabels(list);
}

bool TableViewEx::eventFilter(QObject *object, QEvent *event)
{
//    qDebug() << event->type();
    if (object == this && event->type() == QEvent::ContextMenu)
    {
        if (m_model->rowCount() == 0)
        {
            QMenu *menu = new QMenu();
            menu->addAction(tr("add"));
            QAction *action = menu->exec(cursor().pos());
            if (action != nullptr)
            {
                QList<QStandardItem*> list;
//                m_model->insertRow(0, list);
                m_model->appendRow(list);
            }
            menu->deleteLater();
        }
        else if (currentIndex().isValid())
        {
            QMenu *menu = new QMenu();
            menu->addAction(tr("insert"));
            menu->addAction(tr("delete"));
            menu->addAction(tr("clear"));

            QAction *action = menu->exec(cursor().pos());
            if (action != nullptr)
            {
                if (action->text().compare(tr("insert")) == 0)
                {
                    QList<QStandardItem*> list;
                    m_model->insertRow(currentIndex().row() + 1, list);
//                    QStandardItem *item = new QStandardItem();
//                    m_model->insertRow(currentIndex().row(), item);
                }
                else if (action->text().compare(tr("delete")) == 0)
                {
                    m_model->removeRow(currentIndex().row());
                }
                else if (action->text().compare(tr("clear")) == 0)
                {
                    m_model->removeRows(0, m_model->rowCount());
                }
            }
            menu->deleteLater();
        }
    }

    return QTableView::eventFilter(object, event);
}

